<template>
  <div class="wrap">
    <div class="content-box">
      <img :src="infoData.BackgroundMaterialShow" id="img_mater" class="mater" ref="materialImg"
        v-if="infoData.isMaterialImg" />
      <video id="videoBox" class="mater" ref="materialVideo" controls autoplay loop preload="auto"
        :src="infoData.BackgroundMaterialShow" v-if="infoData.isMaterialVideo">
      </video>
      <!-- <div id="box" class="worship-item" v-show="infoData.isMaterialImg">
        <div class="text-wrap">
          <p class="content" id="contentbox"></p>
        </div>
      </div> -->
      <audio class="audio_wrap" ref="audioref" :src="`${infoData.backgroundMusic}`" controls autoplay loop>
      </audio>
    </div>
    <img :src="infoData.BackgroundImageShow" class="wrap_bg video_bg" v-if="infoData.isBackImg" />

    <video class="video_bg" id="video_bg_box" :src="infoData.BackgroundImageShow" @loadedmetadata="onVideoLoad"
      ref="bgVideo" autoplay loop preload="auto" :poster="poster" v-if="!infoData.isBackImg">
    </video>
  </div>
</template>
<script setup name="deceased">
import { onMounted, onBeforeUnmount, ref, defineProps, watch, nextTick } from 'vue';
import { baseUrl } from '../utils/http'
//import poster from '@/assets/img/grey.png'
//import { checkImgExists, checkVideoExists, checkAudioExists } from '../utils/util'
// import gsap from "gsap";
// import { TextPlugin } from "gsap/TextPlugin"; // 导入 TextPlugin


// gsap.registerPlugin(TextPlugin); // 注册插件
const audioref = ref(null)
const materialImg = ref(null)
const materialVideo = ref(null)
const bgImg = ref(null)
const bgVideo = ref(null)
const originH = ref('');
const originW = ref('');
const materialImgL = ref(0)
const materialVideoL = ref(0)
const heightRef = ref('')
const infoData = ref({})
const poster = ref('')
const props = defineProps({
  data: {
    type: Object,
    default: () => { }
  }
})

/**
 * 从视频中抓取第一帧，生成 base64 poster
 * @param {String} src 视频 URL
 * @returns {Promise<String>} Promise resolves to dataURL
 */
 function captureFirstFrame(src) {
  return new Promise((resolve, reject) => {
    const vid = document.createElement('video')
    vid.crossOrigin = 'anonymous'   // 如果是跨域资源，需要服务端允许 CORS
    vid.src = src
    vid.preload = 'metadata'
    vid.muted = true                // 某些浏览器需要静音才能 autoplay/seek

    // 1. metadata 加载后可以拿到 videoWidth/videoHeight
    vid.addEventListener('loadedmetadata', () => {
      // 有些视频第一帧可能是全黑，跳到 0.1s 更保险
      vid.currentTime = 0.1
    })

    // 2. 跳帧完成后，把这一帧画到 canvas
    vid.addEventListener('seeked', () => {
      const w = vid.videoWidth
      const h = vid.videoHeight
      const canvas = document.createElement('canvas')
      canvas.width  = w
      canvas.height = h
      const ctx = canvas.getContext('2d')
      ctx.drawImage(vid, 0, 0, w, h)
      // 3. 导出 base64
      try {
        const dataURL = canvas.toDataURL('image/png')
        resolve(dataURL)
      } catch (err) {
        reject(err)
      }
    })

    // 错误处理
    vid.addEventListener('error', e => {
      reject(new Error('视频加载失败'))
    })
  })
 }




// 监听播放状态
const playVideo = async () => {
  try {
    await bgVideo.value.play();
    //showWarning.value = false; // 播放成功后隐藏提示
    console.error("视频播放成功");
  } catch (error) {
    console.error("视频播放错误:", error);
    //showWarning.value = true; // 播放失败，显示提示
  }
};

// 加载图片并返回图片元素
const loadImage = (imageUrl) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = imageUrl;
    img.onload = () => {
      console.log(true)
      resolve(true);
    };

    img.onerror = () => {
      resolve(false);
    };
  });
};


const config = import.meta.env.VITE_PACKAGE_CONFIG;
// 当前屏幕宽度
const screenWidth = ref(window.innerWidth)

watch(() => props.data, async (val) => {
  //console.log('deceased', val)
  if (!Object.keys(val).length) { return; }
  const obj = val;
  const numFile = obj.CeremonyOrdersID;
  // const bgMater = numFile + '/' + obj.BackgroundImage;
  // const mater = numFile + '/' + obj.BackgroundMaterial;
  // const music = numFile + '/' + obj.backgroundMusic;
  // const bgMater_online = baseUrl + '/' + obj.BackgroundImage;
  // const mater_online = baseUrl + '/' + obj.BackgroundMaterial;
  // const music_online = obj.backgroundMusic ? baseUrl + '/' + obj.backgroundMusic : ''
  if (config == 'online') {
    obj.BackgroundImageShow = baseUrl + '/' + obj.BackgroundImage;
    obj.BackgroundMaterialShow = obj.BackgroundMaterial ? baseUrl + '/' + obj.BackgroundMaterial : '';
    obj.backgroundMusic = obj.backgroundMusic ? baseUrl + '/' + obj.backgroundMusic : ''
  } else {
    poster.value = `${obj.BackgroundImageLocal?.split('.mp4')?.[0]}.jpg`

    obj.BackgroundImageShow = obj.BackgroundImageLocal;
    obj.BackgroundMaterialShow = obj.BackgroundMaterialLocal;
    obj.backgroundMusic = obj.backgroundMusicLocal;
  }

  infoData.value = obj;
}, {
  deep: true,
  immediate: true
})



// 更新屏幕尺寸
function updateScreenSize() {
  screenWidth.value = window.innerWidth
}




onMounted(() => {

  //showFullScreenPrompt()
  //const playbtn = document.querySelector('#playbtn');
  // setInitfn()
  // if (infoData.value.BackgroundImageShow) {
  //   if (infoData.value.isBackImg) {
  //     setInitImgfn(obj.BackgroundImageShow)
  //   } else {
  //     setInitfn(infoData.value.BackgroundImageShow)
  //   }
  // }
  // const img_mater = document.querySelector('#img_mater')
  // console.log('img_mater',img_mater)
})

onBeforeUnmount(() => {
  //window.removeEventListener('resize', updateScreenSize)
})
</script>
<style lang="less" scoped>
@w: 1920vw;
@rw: (@w/100);
@h: 1080vh;
@rh: (@h/100);

.adaptive-size(@elementWidth, @elementHeight, @baseWidth: 1920, @baseHeight: 1080) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  @heightRatio: (@elementHeight / @baseHeight) * 100;
  width: @widthRatio * 1vw;
  height: @heightRatio * 1vh;
}

.adaptive-font(@elementWidth, @baseWidth: 1920) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  font-size: @widthRatio * 1vw;
}

.wrap {
  // width: 100vw;
  // height: 100%;
  //background: url('../assets/img/bg.webp') no-repeat;
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  overflow-y: hidden;


  .content-box {
    position: relative;
    display: flex;
    align-items: center;
    height: 100vh;
    box-sizing: border-box;

    .avator {
      object-fit: contain;
      /* 确保视频填满屏幕，且保持视频比例 */
      object-position: center;
    }

    .text-wrap {
      margin-left: 20px;
      font-size: (40vw / @rw);
      color: #fff;

      .left {
        font-weight: bold;
      }
    }
  }

  .mater {
    // width: 100vw;
    // height: 100vh;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    object-fit: contain;
    /* 确保视频填满屏幕，且保持视频比例 */
    object-position: center;
    background-color: transparent;
    /* 背景颜色，避免视频比例问题时的黑边 */
  }

}

.video_bg {
  position: absolute;
  left: 0;
  top: 0;
  //width: 100vw;
  //height: 100%;
  z-index: -2;
  //object-fit: cover; /* 确保视频填满屏幕，且保持视频比例 */
  background-color: transparent;
  /* 背景颜色，避免视频比例问题时的黑边 */
}

.audio_wrap {
  position: absolute;
  left: 0;
  margin: 30px 0 0 0;
  opacity: 0;
  display: none;

}
</style>